package dao

import (
	"github.com/gin-gonic/gin"
	"github.com/youkelike/gateway/core/lib"
	"gorm.io/gorm"
)

type CircuitConfig struct {
	ID                     int64  `json:"id" gorm:"primary_key"`
	ServiceID              int64  `json:"service_id" gorm:"column:service_id" description:"服务id"`
	ServiceName            string `json:"service_name" gorm:"column:service_name" description:"服务名"`
	Timeout                int    `json:"timeout" gorm:"column:timeout" description:"单次请求超时时长"`
	MaxConcurrentRequests  int    `json:"max_concurrent_requests" gorm:"column:max_concurrent_requests" description:"最大并发"`
	RequestVolumeThreshold int    `json:"request_volume_threshold" gorm:"column:request_volume_threshold" description:"统计每10s内请求数"`
	SleepWindow            int    `json:"sleep_window" gorm:"column:sleep_window" description:"熔断后再次尝试间隔"`
	ErrorPercentThreshold  int    `json:"error_percent_threshold" gorm:"column:error_percent_threshold" description:"统计错误百分比"`
	FallBackMsg            string `json:"fall_back_msg" gorm:"column:fall_back_msg" description:"降级消息"`
	NeedCircuit            int    `json:"need_circuit" gorm:"column:need_circuit" description:"功能启停开关"` //0: close, 1: open
}

func (c *CircuitConfig) TableName() string {
	return "gateway_circuit_config"
}

func (ci *CircuitConfig) Find(c *gin.Context, tx *gorm.DB, search *CircuitConfig) (*CircuitConfig, error) {
	model := &CircuitConfig{}
	err := tx.WithContext(lib.NewTraceContext(c)).Where(search).Find(model).Error
	if err != nil {
		return nil, err
	}
	return model, nil
}

func (ci *CircuitConfig) Save(c *gin.Context, tx *gorm.DB) error {
	if err := tx.WithContext(lib.NewTraceContext(c)).Save(ci).Error; err != nil {
		return err
	}
	return nil
}

func (ci *CircuitConfig) FindAll(c *gin.Context, tx *gorm.DB) ([]CircuitConfig, error) {
	var res []CircuitConfig
	query := tx.WithContext(lib.NewTraceContext(c))
	query = query.Table(ci.TableName()).Select("*").Where("need_circuit=?", 1)
	err := query.Find(&res).Error
	if err != nil {
		return nil, err
	}
	return res, nil

}
